/**
 * 
 */
package finn.movingheadtracker;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Panel;
import java.util.Iterator;
import java.util.List;

import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamPanel;

/**
 * @author FinnHermeling
 * 
 */
//TODO Add Function isValid or isAvailable
public class Cameraview extends Camera{
	public String sourcetype;
	public String source;
	/**
	 * 
	 */
	public Cameraview() {
	}
	/**
	 * 
	 * @param sourcetype
	 * @param source Can be Name of WebcamDevice.getName() or IP of Stream
	 */
	public void setSource(String sourcetype, String source){
		switch(sourcetype){
			case "http":
				this.sourcetype="http";
				this.source=source;
			case "webcam":
				this.sourcetype="webcam";
				this.source=source;
		}
	}
	
	public Component getPanel(){
		switch(this.sourcetype){
			case "http":
			case "webcam":
				Webcam cam = this.getCamerabyName(this.source);
				try {
					cam.setViewSize(res);
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					System.out.print("[" + res.height + "," + res.width + "] Wrong dimensions! Possible ressolutions:");
					for(Dimension dim : cam.getViewSizes()){
						System.out.print("[" + dim.height + "," + dim.width + "]");
					}
					System.out.println();
					return new Panel();
				}
				return new WebcamPanel(cam);
		}
		return null;
	}
	
	public Webcam getCamerabyName(String name){
		Webcam cam;
		List<Webcam> cams = Webcam.getWebcams();
		for(Iterator<Webcam> it = cams.iterator(); it.hasNext();){
			cam=it.next();
			if(cam.getName().contains(name)){
				return cam;
			}
		}
		return null;
	}
	@Override
	public String toString(){
		return String.valueOf(this.id) + " - " + this.name;
	}
	
	public String getStringResolution(){
		return String.valueOf((int)res.getHeight()) + ":" + String.valueOf((int)res.getWidth());
	}
	
	public void setStringResolution(String res){
		String[] results = res.split(":",2);
		this.res = new Dimension(Integer.parseInt(results[1]), Integer.parseInt(results[0]));
	}
}
